package com.hirsi.common.core.config;

import cn.hutool.core.collection.CollUtil;
import com.hirsi.common.core.handler.RequestMethodProcessor;
import com.hirsi.common.core.interceptor.IHandlerInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

/**
 * web配置
 */
@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    //扫描到的拦截器，可以为空
    @Autowired(required = false)
    private List<IHandlerInterceptor> interceptors;

    //swagger相关接口不拦截
    private final String[] swaggerPaths = {"/doc.html", "/swagger-resources/**", "/webjars/**", "/v3/**", "/favicon.ico"};

    /**
     * 拦截器配置
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        if (CollUtil.isNotEmpty(interceptors)) {
            interceptors.forEach(interceptor -> registry.addInterceptor(interceptor)
                    .addPathPatterns(interceptor.addPaths())
                    .excludePathPatterns("/error")
                    .excludePathPatterns(swaggerPaths)
                    .excludePathPatterns(interceptor.excludePaths()));
        }
    }

    /**
     * 跨域配置
     * @param registry
     */
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**") // 所有接口
                .allowCredentials(true) // 是否发送 Cookie
                .allowedOrigins("*") // 支持域
                .allowedMethods("GET", "POST", "PUT", "DELETE") // 支持方法
                .allowedHeaders("*")
                .exposedHeaders("*");
    }

    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(new RequestMethodProcessor());
    }
}
